# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models
from django.db.models.loading import cache

from .fields import CrossForeignIntegerField


# 缓存大表的count的基类
class ELBaseModel(models.Model):
    class Meta:
        abstract = True

    def get_total_count(self):
        from wlmodels.dataplus.models import ELCount
        the_count = ELCount.objects.filter(table=self._meta.db_table).first()
        if the_count:
            return the_count.count

        try:
            applabel, model_name = str(self._meta).split(".")
            the_model = cache.app_models[applabel][model_name.lower()]
            return the_model.objects.all().count()
        except KeyError:
            return 0


# 编码表抽象类
class ELCode(models.Model):
    code = models.CharField('编码', max_length=10, unique=True)
    parent = models.ForeignKey('self', verbose_name='上级地区', null=True, blank=True,
                               db_column='parent', to_field='code', related_name='+', on_delete=models.SET(''))
    name = models.CharField('意义', max_length=20)

    class Meta:
        abstract = True

    def __unicode__(self):
        return u'%s' % self.name


# 行政区域代码表
class ELRegion(ELCode):
    level = models.CharField('级别', max_length=1, choices=(('1', '1'), ('2', '2'), ('3', '3'),))
    fulltitle = models.CharField('地名全称', max_length=40)
    zipcode = models.CharField('邮编', max_length=10, blank=True)
    lnglat = models.CharField('经纬度', max_length=20, blank=True)

    class Meta:
        verbose_name = '行政区域'
        verbose_name_plural = '行政区域'
        db_table = 'code_region'

    # 根据行政地区编码获取地区全名，处理编码不一致的问题
    @staticmethod
    def get_region(c, m="name"):
        if isinstance(c, basestring) and len(c) == 6:
            the_r = ELRegion.objects.filter(code=c)
            if the_r.count() == 0:
                the_r = ELRegion.objects.filter(code=(c[:-2] + "00"))
                if the_r.count() == 0:
                    the_r = ELRegion.objects.filter(code=(c[:-4] + "00"))
            if the_r.count():
                if m == "obj":
                    return the_r[0]
                elif m == "fulltitle":
                    return the_r[0].fulltitle
                else:
                    return the_r[0].name
        return ""


# 行业分类
class ELNic(ELCode):
    scode = models.CharField('小类编码', max_length=5, db_index=True)
    level = models.CharField('分类级别', max_length=1, choices=(('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'),))
    fulltitle = models.CharField('分类全称', max_length=80)

    class Meta:
        verbose_name = '行业分类'
        verbose_name_plural = '行业分类'
        db_table = 'code_nic'


# 经济行业分类表
class ELSeic(ELCode):
    level = models.CharField('分类级别', max_length=1, choices=(('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'),))
    fulltitle = models.CharField('分类全称', max_length=80)

    class Meta:
        verbose_name = '战兴分类'
        verbose_name_plural = '战兴产业分类'
        db_table = 'code_seic'


# 企业注册登记类型表（税务专用）
class ELRegisterTypeTax(ELCode):
    class Meta:
        verbose_name = '经济类型（税务）'
        verbose_name_plural = '经济类型（税务）'
        db_table = 'code_registertype'


# 海关商品编码表
class ELHGGoodsCode(ELCode):
    level = models.CharField('级别', max_length=1, choices=(('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'),))
    fulltitle = models.TextField('全称')

    class Meta:
        verbose_name = '海关商品编码表'
        verbose_name_plural = '海关商品编码表'
        db_table = 'code_hg_goods'


# 国家CA02
class ELCA02(ELCode):
    class Meta:
        verbose_name = '国家CA02'
        verbose_name_plural = '国家CA02'
        db_table = 'code_ca02'


# 币种CA04
class ELCA04(ELCode):
    class Meta:
        verbose_name = '币种CA04'
        verbose_name_plural = '币种CA04'
        db_table = 'code_ca04'


# 登记机关CA11
class ELCA11(ELCode):
    class Meta:
        verbose_name = '登记机关CA11'
        verbose_name_plural = '登记机关CA11'
        db_table = 'code_ca11'


# 工商所CA12
class ELCA12(ELCode):
    class Meta:
        verbose_name = '工商所CA12'
        verbose_name_plural = '工商所CA12'
        db_table = 'code_ca12'


# 企业类型CA16
class ELCA16(ELCode):
    level = models.CharField('级别', max_length=1, choices=(('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'),))

    class Meta:
        verbose_name = '企业类型CA16'
        verbose_name_plural = '企业类型CA16'
        db_table = 'code_ca16'


# 行政许可CA25
class ELCA25(ELCode):
    class Meta:
        verbose_name = '行政许可CA25'
        verbose_name_plural = '行政许可CA25'
        db_table = 'code_ca25'


# 经济开发区CA73
class ELCA73(ELCode):
    class Meta:
        verbose_name = '经济开发区CA73'
        verbose_name_plural = '经济开发区CA73'
        db_table = 'code_ca73'


# 外资产业CA75
class ELCA75(ELCode):
    class Meta:
        verbose_name = '外资产业CA75'
        verbose_name_plural = '外资产业CA75'
        db_table = 'code_ca75'


# 中西部优势产业CA76
class ELCA76(ELCode):
    class Meta:
        verbose_name = '中西部优势产业CA76'
        verbose_name_plural = '中西部优势产业CA76'
        db_table = 'code_ca76'


# 商标类型CC01
class ELCC01(ELCode):
    class Meta:
        verbose_name = '商标类型CC01'
        verbose_name_plural = '商标类型CC01'
        db_table = 'code_cc01'


# 违法行为CE02
class ELCE02(ELCode):
    class Meta:
        verbose_name = '违法行为CE02'
        verbose_name_plural = '违法行为CE02'
        db_table = 'code_ce02'


# 处罚依据CE10
class ELCE10(ELCode):
    class Meta:
        verbose_name = '处罚依据CE10'
        verbose_name_plural = '处罚依据CE10'
        db_table = 'code_ce10'


####################################################
########### 各种抽象类 ################################
####################################################

# 关联企业库抽象类
class EntIdable(ELBaseModel):
    entid_id = CrossForeignIntegerField('关联企业', db_column="entid", db_index=True, default=0, null=False, blank=True)

    class Meta:
        abstract = True

    def _entid(self):
        from wlmodels.company.models import ELPost
        if 0 < self.entid_id < 500000000:
            the_ent = ELPost.objects.filter(entid=self.entid_id).first()
            if the_ent:
                return the_ent
        elif self.entid_id >= 500000000:
            from wlmodels.company.models import ELGeti
            the_ent = ELGeti.objects.filter(entid=self.entid_id).first()
            if the_ent:
                return the_ent
        return ELPost()

    _entid.short_description = "关联企业"

    entid = property(_entid)


# 后台跨数据库的外键控件专用的抽象类
class CrossForeignKeys(models.Model):
    entid = models.ForeignKey('company.ELPost', verbose_name='关联企业', to_field='entid', null=True, blank=True,
                              related_name='+', on_delete=models.SET_NULL)
    region_id = models.ForeignKey('codes.ELRegion', verbose_name='所在地区', null=True, blank=True,
                                  to_field='code', related_name='+', on_delete=models.SET_NULL)
    COUNTRY = models.ForeignKey('codes.ELCA02', verbose_name='国别(地区)', null=True, blank=True,
                                to_field='code', related_name='+', on_delete=models.SET_NULL)
    nic_id = models.ForeignKey('codes.ELNic', verbose_name='行业分类', null=True, blank=True,
                               to_field='code', related_name='+', on_delete=models.SET_NULL)
    el_nic_id = models.ForeignKey('codes.ELNic', verbose_name='行业分类', null=True, blank=True,
                                  to_field='code', related_name='+', on_delete=models.SET_NULL)
    el_seic_id = models.ForeignKey('codes.ELSeic', verbose_name='战兴产业分类', null=True, blank=True,
                                   to_field='code', related_name='+', on_delete=models.SET_NULL)
    registertype = models.ForeignKey('codes.ELRegisterTypeTax', verbose_name='经济类型', null=True, blank=True,
                                     to_field='code', related_name='+', on_delete=models.SET_NULL)
    ENTTYPE = models.ForeignKey('codes.ELCA16', verbose_name='企业(机构)类型', null=True, blank=True,
                                to_field='code', related_name='+', on_delete=models.SET_NULL)
    REGORG = models.ForeignKey('codes.ELCA11', verbose_name='登记机关', null=True, blank=True,
                               to_field='code', related_name='+', on_delete=models.SET_NULL)
    DOMDISTRICT = models.ForeignKey('codes.ELRegion', verbose_name='住所所在行政区划', null=True, blank=True,
                                    to_field='code', related_name='+', on_delete=models.SET_NULL)
    OPLOCDISTRICT = models.ForeignKey('codes.ELRegion', verbose_name='经营场所所在行政区划', null=True, blank=True,
                                      to_field='code', related_name='+', on_delete=models.SET_NULL)
    CASESCEDISTRICT = models.ForeignKey('codes.ELRegion', verbose_name='行政区划', null=True, blank=True,
                                        to_field='code', related_name='+', on_delete=models.SET_NULL)
    LOCALADM = models.ForeignKey('codes.ELCA12', verbose_name='属地监管工商所', null=True, blank=True,
                                 to_field='code', related_name='+', on_delete=models.SET_NULL)
    ECOTECDEVZONE = models.ForeignKey('codes.ELCA73', verbose_name='属地监管工商所', null=True, blank=True,
                                      to_field='code', related_name='+', on_delete=models.SET_NULL)
    FORCAPINDCODE = models.ForeignKey('codes.ELCA75', verbose_name='外资产业代码', null=True, blank=True,
                                      to_field='code', related_name='+', on_delete=models.SET_NULL)
    MIDPREINDCODE = models.ForeignKey('codes.ELCA76', verbose_name='中西部优势产业代码', null=True, blank=True,
                                      to_field='code', related_name='+', on_delete=models.SET_NULL)
    CURRENCY = models.ForeignKey('codes.ELCA04', verbose_name='币种', null=True, blank=True,
                                 to_field='code', related_name='+', on_delete=models.SET_NULL)
    CONGROCUR = models.ForeignKey('codes.ELCA04', verbose_name='投资总额币种', null=True, blank=True,
                                  to_field='code', related_name='+', on_delete=models.SET_NULL)
    REGCAPCUR = models.ForeignKey('codes.ELCA04', verbose_name='注册资本(金)币种', null=True, blank=True,
                                  to_field='code', related_name='+', on_delete=models.SET_NULL)
    RECCAPCUR = models.ForeignKey('codes.ELCA04', verbose_name='实收资本(金)币种', null=True, blank=True,
                                  to_field='code', related_name='+', on_delete=models.SET_NULL)
    DOMEREGCAPCUR = models.ForeignKey('codes.ELCA04', verbose_name='中方注册资本(金)币种', null=True, blank=True,
                                      to_field='code', related_name='+', on_delete=models.SET_NULL)
    DOMERECCAPCUR = models.ForeignKey('codes.ELCA04', verbose_name='中方实收资本(金)币种', null=True, blank=True,
                                      to_field='code', related_name='+', on_delete=models.SET_NULL)
    FORREGCAPCUR = models.ForeignKey('codes.ELCA04', verbose_name='外方注册资本(金)币种', null=True, blank=True,
                                     to_field='code', related_name='+', on_delete=models.SET_NULL)
    FORRECCAPCUR = models.ForeignKey('codes.ELCA04', verbose_name='外方实收资本(金)币种', null=True, blank=True,
                                     to_field='code', related_name='+', on_delete=models.SET_NULL)
    OPERAREA = models.ForeignKey('codes.ELRegion', verbose_name='经营者所在地区', null=True, blank=True,
                                 to_field='code', related_name='+', on_delete=models.SET_NULL)
    NAMEDISTRICT = models.ForeignKey('codes.ELRegion', verbose_name='名称行政区域', null=True, blank=True,
                                     to_field='code', related_name='+', on_delete=models.SET_NULL)
    APPRAUTH = models.ForeignKey('codes.ELCA11', verbose_name='核准机关', null=True, blank=True,
                                 to_field='code', related_name='+', on_delete=models.SET_NULL)
    PREREGORG = models.ForeignKey('codes.ELCA11', verbose_name='规定登记机关', null=True, blank=True,
                                  to_field='code', related_name='+', on_delete=models.SET_NULL)
    ILLEGACTTYPE = models.ForeignKey('codes.ELCE02', verbose_name='违法行为种类', null=True, blank=True,
                                     to_field='code', related_name='+', on_delete=models.SET_NULL)
    QUAGIST = models.ForeignKey('codes.ELCE10', verbose_name='定性依据', null=True, blank=True,
                                to_field='code', related_name='+', on_delete=models.SET_NULL)
    PENBASIS = models.ForeignKey('codes.ELCE10', verbose_name='处罚依据', null=True, blank=True,
                                 to_field='code', related_name='+', on_delete=models.SET_NULL)
    PENAUTH = models.ForeignKey('codes.ELCA11', verbose_name='处罚机关', null=True, blank=True,
                                to_field='code', related_name='+', on_delete=models.SET_NULL)
    LICNAME = models.ForeignKey('codes.ELCA25', verbose_name='许可证书', null=True, blank=True,
                                to_field='code', related_name='+', on_delete=models.SET_NULL)
    MOUTAREREGORG = models.ForeignKey('codes.ELCA11', verbose_name='迁出地登记机关', null=True, blank=True,
                                      to_field='code', related_name='+', on_delete=models.SET_NULL)
    MINAREREGORG = models.ForeignKey('codes.ELCA11', verbose_name='迁入地登记机关', null=True, blank=True,
                                     to_field='code', related_name='+', on_delete=models.SET_NULL)
    TMTYPE = models.ForeignKey('codes.ELCC01', verbose_name='商标类别', null=True, blank=True,
                               to_field='code', related_name='+', on_delete=models.SET_NULL)
    IntCls = models.ForeignKey('codes.ELCC01', verbose_name='国际商标分类', null=True, blank=True,
                               to_field='code', related_name='+', on_delete=models.SET_NULL)

    class Meta:
        abstract = True
